import sys, io
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QHBoxLayout, QPushButton, QLabel, QLineEdit,
                             QTextEdit, QMessageBox, QTabWidget, QInputDialog)
from PyQt5.QtCore import Qt
import datetime

# 导入原有业务逻辑模块
from util import public_tools as tool
from service import hr_service as hr
from util import camera


class AttendanceSystem(QMainWindow):
    def __init__(self):
        super().__init__()
        self.admin_login = False
        self.init_ui()
        # 初始化数据
        hr.load_emp_data()

    def init_ui(self):
        self.setWindowTitle("智能视频打卡系统")
        self.setGeometry(100, 100, 800, 600)

        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)

        # 顶部状态显示
        self.status_label = QLabel("当前状态：未登录 | 请选择功能")
        main_layout.addWidget(self.status_label)

        # 功能标签页
        self.tabs = QTabWidget()
        main_layout.addWidget(self.tabs)

        # 1. 打卡标签页
        self.checkin_tab = QWidget()
        self.init_checkin_tab()
        self.tabs.addTab(self.checkin_tab, "打卡")

        # 2. 查看记录标签页
        self.record_tab = QWidget()
        self.init_record_tab()
        self.tabs.addTab(self.record_tab, "查看记录")

        # 3. 员工管理标签页
        self.employee_tab = QWidget()
        self.init_employee_tab()
        self.tabs.addTab(self.employee_tab, "员工管理")

        # 4. 考勤报表标签页
        self.report_tab = QWidget()
        self.init_report_tab()
        self.tabs.addTab(self.report_tab, "考勤报表")

        # 5. 系统设置标签页
        self.settings_tab = QWidget()
        self.init_settings_tab()
        self.tabs.addTab(self.settings_tab, "设置")

        # 底部按钮
        btn_layout = QHBoxLayout()
        self.login_btn = QPushButton("管理员登录")
        self.login_btn.clicked.connect(self.admin_login_func)
        self.exit_btn = QPushButton("退出系统")
        self.exit_btn.clicked.connect(self.close)

        btn_layout.addWidget(self.login_btn)
        btn_layout.addWidget(self.exit_btn)
        main_layout.addLayout(btn_layout)

        # 更新界面状态
        self.update_ui_state()

    def init_checkin_tab(self):
        layout = QVBoxLayout(self.checkin_tab)
        self.checkin_status = QLabel("请点击下方按钮进行人脸打卡")
        self.checkin_btn = QPushButton("开始人脸打卡")
        self.checkin_btn.clicked.connect(self.face_checkin)

        layout.addWidget(self.checkin_status, alignment=Qt.AlignCenter)
        layout.addWidget(self.checkin_btn)

    def init_record_tab(self):
        layout = QVBoxLayout(self.record_tab)
        btn_layout = QHBoxLayout()

        self.show_employees_btn = QPushButton("查看员工列表")
        self.show_employees_btn.clicked.connect(self.show_employees)
        self.show_records_btn = QPushButton("查看打卡记录")
        self.show_records_btn.clicked.connect(self.show_all_records)

        btn_layout.addWidget(self.show_employees_btn)
        btn_layout.addWidget(self.show_records_btn)

        self.records_display = QTextEdit()
        self.records_display.setReadOnly(True)

        layout.addLayout(btn_layout)
        layout.addWidget(self.records_display)

    def init_employee_tab(self):
        layout = QVBoxLayout(self.employee_tab)
        btn_layout = QHBoxLayout()

        self.add_employee_btn = QPushButton("添加新员工")
        self.add_employee_btn.clicked.connect(self.add_employee)
        self.delete_employee_btn = QPushButton("删除员工")
        self.delete_employee_btn.clicked.connect(self.delete_employee)

        btn_layout.addWidget(self.add_employee_btn)
        btn_layout.addWidget(self.delete_employee_btn)

        self.employee_display = QTextEdit()
        self.employee_display.setReadOnly(True)

        layout.addLayout(btn_layout)
        layout.addWidget(self.employee_display)

    def init_report_tab(self):
        layout = QVBoxLayout(self.report_tab)
        btn_layout = QHBoxLayout()

        self.daily_report_btn = QPushButton("日报表")
        self.daily_report_btn.clicked.connect(self.show_daily_report)
        self.monthly_report_btn = QPushButton("月报表")
        self.monthly_report_btn.clicked.connect(self.show_monthly_report)

        btn_layout.addWidget(self.daily_report_btn)
        btn_layout.addWidget(self.monthly_report_btn)

        self.report_display = QTextEdit()
        self.report_display.setReadOnly(True)

        layout.addLayout(btn_layout)
        layout.addWidget(self.report_display)

    def init_settings_tab(self):
        layout = QVBoxLayout(self.settings_tab)

        self.work_time_label = QLabel("上班时间:")
        self.work_time_input = QLineEdit("09:00:00")
        self.close_time_label = QLabel("下班时间:")
        self.close_time_input = QLineEdit("17:00:00")
        self.save_time_btn = QPushButton("保存作息时间设置")
        self.save_time_btn.clicked.connect(self.save_work_time)

        layout.addWidget(self.work_time_label)
        layout.addWidget(self.work_time_input)
        layout.addWidget(self.close_time_label)
        layout.addWidget(self.close_time_input)
        layout.addWidget(self.save_time_btn)

    def update_ui_state(self):
        # 根据登录状态更新界面元素可用性
        if self.admin_login:
            self.status_label.setText("当前状态：管理员已登录")
            self.login_btn.setText("退出登录")
            # 管理员可以使用所有功能
            for btn in [self.show_employees_btn, self.show_records_btn,
                        self.add_employee_btn, self.delete_employee_btn,
                        self.daily_report_btn, self.monthly_report_btn,
                        self.save_time_btn]:
                btn.setEnabled(True)
        else:
            self.status_label.setText("当前状态：未登录 | 仅可使用打卡功能")
            self.login_btn.setText("管理员登录")
            # 非管理员只能使用打卡功能
            for btn in [self.show_employees_btn, self.show_records_btn,
                        self.add_employee_btn, self.delete_employee_btn,
                        self.daily_report_btn, self.monthly_report_btn,
                        self.save_time_btn]:
                btn.setEnabled(False)

    def admin_login_func(self):
        if self.admin_login:
            # 退出登录
            self.admin_login = False
            self.update_ui_state()
            QMessageBox.information(self, "提示", "已退出登录")
            return

        # 登录流程
        username, ok = QInputDialog.getText(self, "登录", "请输入管理员账号:")
        if not ok or username == "":
            return

        password, ok = QInputDialog.getText(self, "登录", "请输入管理员密码:", echo=QLineEdit.Password)
        if not ok:
            return

        if hr.valid_users(username.strip(), password.strip()):
            self.admin_login = True
            self.update_ui_state()
            QMessageBox.information(self, "成功", f"{username} 登录成功")
        else:
            QMessageBox.warning(self, "错误", "账号或密码错误")

    def face_checkin(self):
        self.checkin_status.setText("请正面对准摄像头进行打卡...")
        QApplication.processEvents()  # 刷新界面

        name = camera.clock_in()
        if name:
            hr.add_lock_record(name)
            self.checkin_status.setText(f"      {name} 打卡成功！\n"
                                        f"时间：{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        else:
            self.checkin_status.setText("打卡失败，请重试")

    def show_employees(self):
        report = hr.get_employee_report()
        self.records_display.setText(report)

    def show_all_records(self):
        report = hr.get_record_all()
        self.records_display.setText(report)

    def add_employee(self):
        name, ok = QInputDialog.getText(self, "添加员工", "请输入新员工姓名:")
        if not ok or name.strip() == "" or name == "0":
            return

        code = hr.add_new_employee(name)
        QMessageBox.information(self, "提示", "请面对摄像头，按3次Enter键完成拍照！")
        camera.register(code)
        self.employee_display.setText(hr.get_employee_report())
        QMessageBox.information(self, "特征码", code)
        QMessageBox.information(self, "成功", f"{name}员工添加成功")

    def delete_employee(self):
        # 显示员工列表
        self.employee_display.setText(hr.get_employee_report())

        id_text, ok = QInputDialog.getText(self, "删除员工", "请输入要删除的员工编号:")
        if not ok or id_text == "0":
            return

        try:
            emp_id = int(id_text)
            if not hr.check_id(emp_id):
                QMessageBox.warning(self, "错误", "无此员工")
                return

            # 生成验证码
            verification = tool.randomNumber(4)
            input_ver, ok = QInputDialog.getText(self, "验证", f"请输入验证码: {verification}")
            if not ok:
                return

            if str(verification) == input_ver.strip():
                hr.remove_employee(emp_id)
                self.employee_display.setText(hr.get_employee_report())
                QMessageBox.information(self, "成功", f"{emp_id}号员工已删除")
            else:
                QMessageBox.warning(self, "错误", "验证码有误，操作取消")

        except ValueError:
            QMessageBox.warning(self, "错误", "请输入有效的员工编号")

    def show_daily_report(self):

        old_stdout = sys.stdout
        new_stdout = io.StringIO()
        sys.stdout = new_stdout

        date, ok = QInputDialog.getText(self, "日报表", "输入查询日期(格式:2025-07-08),输入0查询今天:")
        if not ok:
            return
        self.clear_report_display()
        try:
            if date == "0":
                hr.get_today_report()
                today = datetime.datetime.now().strftime("%Y-%m-%d")
                title = f"===== {today} 考勤日报 ====="
            elif tool.valid_data(date):
                hr.get_day_report(date)
                title = f"===== {date} 考勤日报 ====="
            else:
                QMessageBox.warning(self, "错误", "日期格式有误")
                return

            # 获取捕获的输出
            report_content = new_stdout.getvalue()
            # 显示报表
            self.report_display.setText(f"{title}\n\n{report_content}")
        finally:
            # 恢复标准输出
            sys.stdout = old_stdout


    def show_monthly_report(self):

        old_stdout = sys.stdout
        new_stdout = io.StringIO()
        sys.stdout = new_stdout

        month, ok = QInputDialog.getText(self, "月报表", "输入查询月份(格式:2025-07),输入0查询上月:")
        if not ok:
            return
        self.clear_report_display()
        try:
            if month == "0":
                hr.get_pre_month_report()
                today = datetime.date.today()
                pre_month = (today.month - 2) % 12 + 1
                pre_month_str = f"{today.year}-{pre_month:02d}"
                title = f"===== {pre_month_str} 考勤月报 ====="
            elif tool.valid_year_month(month):
                hr.get_month_report(month)
                title = f"===== {month} 考勤月报 ====="
            else:
                QMessageBox.warning(self, "错误", "月份格式有误")
                return

            # 获取捕获的输出
            report_content = new_stdout.getvalue()
            # 显示报表
            self.report_display.setText(f"{title}\n\n{report_content}")
        finally:
            # 恢复标准输出
            sys.stdout = old_stdout

    def save_work_time(self):
        work_time = self.work_time_input.text()
        close_time = self.close_time_input.text()

        if not tool.valid_time(work_time):
            QMessageBox.warning(self, "错误", "上班时间格式有误")
            return

        if not tool.valid_time(close_time):
            QMessageBox.warning(self, "错误", "下班时间格式有误")
            return

        hr.save_work_time(work_time, close_time)
        QMessageBox.information(self, "成功", f"作息时间设置完成\n上班时间: {work_time}\n下班时间: {close_time}")

    # 新增：清空报表显示的方法
    def clear_report_display(self):
        """清空报表显示区域并重置状态"""
        self.report_display.clear()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AttendanceSystem()
    window.show()
    sys.exit(app.exec_())